package com.minelx.sequence.pattern;

import com.minelx.sequence.core.ReturnMatcher;
import com.minelx.sequence.core.StringScanner;

import java.util.function.Consumer;

public class VariablePatternParser implements ReturnMatcher<ReturnMatcher<?, StringScanner>, StringScanner> {

	private final VariableSettingFactory variableSettingFactory;

	private final PatternParser patternParser;

	public VariablePatternParser(VariableSettingFactory variableSettingFactory, PatternParser patternParser) {
		this.variableSettingFactory = variableSettingFactory;
		this.patternParser = patternParser;
	}

	@Override
	public boolean isMatch(StringScanner clue) {
		return clue.exists("${");
	}

	@Override
	public ReturnMatcher<?, StringScanner> onMatched(StringScanner source) {
		source.goes("${");
		String variableName = source.nextPage();
		source.goes(":");
		ReturnMatcher<?, StringScanner> matcher = patternParser.get(source).orElseThrow(RuntimeException::new);
		source.goes("}");
		Consumer<Object> variableSetter = variableSettingFactory.createVariableSetter(variableName);
		return new AdditionalConsumeMatcher<>(matcher, variableSetter);
	}
}
